package cn.xinyangtong.order.service;

import java.util.Date;
import java.util.List;

import cn.xinyangtong.common.pojo.DefaultResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.xinyangtong.mapper.TbOrderItemMapper;
import cn.xinyangtong.mapper.TbOrderMapper;
import cn.xinyangtong.mapper.TbOrderShippingMapper;
import cn.xinyangtong.pojo.TbOrder;
import cn.xinyangtong.pojo.TbOrderItem;
import cn.xinyangtong.pojo.TbOrderShipping;
import cn.xinyangtong.order.dao.JedisClient;
import cn.xinyangtong.facade.order.OrderService;
import org.springframework.util.StringUtils;

@Service("orderService")
public class OrderServiceImpl implements OrderService {
	@Value("${ORDER_GEN_KEY}")
	private String ORDER_GEN_KEY;
	@Value("${ORDER_INIT_ID}")
	private String ORDER_INIT_ID;
	@Value("${ORDER_DETAIL_GEN_KEY}")
	private String ORDER_DETAIL_GEN_KEY;

	@Autowired
	private TbOrderMapper orderMapper;
	@Autowired
	private TbOrderItemMapper orderItemMapper;
	@Autowired
	private TbOrderShippingMapper orderShippingMapper;
	@Autowired
	private JedisClient jedisClient;

	//生成订单
	@Override
	@Transactional
	public DefaultResult createOrder(TbOrder order, List<TbOrderItem> list,
											TbOrderShipping orderShipping) {
		// 向订单表插入数据
		// 获取订单号，从redis中获取
		String str = jedisClient.get(ORDER_GEN_KEY);
		if (StringUtils.isEmpty(str)) {
			jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID);
		}
		long orderId = jedisClient.incr(ORDER_GEN_KEY);
		order.setOrderId(orderId + "");
		// 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		order.setStatus(1);
		Date date = new Date();
		order.setCreateTime(date);
		order.setUpdateTime(date);
		// 0：未评价 1：已评价
		order.setBuyerRate(0);
		// 向订单表插入数据
		orderMapper.insert(order);
		// 向订单明细表插入数据
		for (TbOrderItem tbOrderItem : list) {
			// 补全订单明细
			// 取订单明细id
			long orderDetailId = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
			tbOrderItem.setId(orderDetailId + "");
			tbOrderItem.setOrderId(orderId + "");
			// 向订单明细插入记录
			orderItemMapper.insert(tbOrderItem);
		}
		// 插入物流表
		orderShipping.setOrderId(orderId + "");
		orderShipping.setCreated(date);
		orderShipping.setUpdated(date);
		orderShippingMapper.insert(orderShipping);
		return DefaultResult.ok(orderId);
	}

	@Override
	public void test() {
		System.out.println("test");
	}

}
